#!/usr/bin/python3
#    pip install python-docx
from docx import Document
import os
from docx.enum.dml import MSO_THEME_COLOR_INDEX
from docx.enum.text import WD_ALIGN_PARAGRAPH

def replace_and_renumber(doc_path, new_doc_path):
    # 打开原始文档
    doc = Document(doc_path)
    
    # 初始化计数器
    count = 1
    
    # 遍历文档中的所有段落
    for para in doc.paragraphs:
        if 'INT.' in para.text:
            tag = "INT."
        elif 'EXT.' in para.text:
            tag = "EXT."
        else:
            tag = ""
        
        if tag!="":
            print(para.text)
            parts = para.text.split(tag)
            new_text = ''
            for part in parts[:-1]:  # 除了最后一个部分，其他都原样加入
                #new_text += part + tag[:-1] + str(count) + '.'
                new_text += f"{part}{count} {tag}"
                count += 1
                
            new_text += parts[-1]  # 添加最后一个分割部分
            para.text = new_text  # 更新段落文本
    
    # 另存为新文件
    doc.save(new_doc_path)
    print(f"文档已转换并保存为：{new_doc_path}")

def replaceName(doc_path, new_doc_path):
    doc = Document(doc_path)   
   
    for para in doc.paragraphs:
        # 检查段落是否居中对齐
        if para.alignment == WD_ALIGN_PARAGRAPH.CENTER or para.alignment == WD_ALIGN_PARAGRAPH.LEFT:
            # 遍历段落中的每一个运行（Run）
            for run in para.runs:
                print(run.text)
                # 检查运行中的字体是否为黑体
                if run.font.bold == True: 
                    print("para bold name")

    # 另存为新文件
    #doc.save(new_doc_path)
    print(f"文档已转换并保存为：{new_doc_path}")
    
current_directory = os.path.dirname(os.path.abspath(__file__))
print(current_directory)

# replace_and_renumber(os.path.join(current_directory,'test.docx'), os.path.join(current_directory,'testnew.docx'))
files = os.listdir(current_directory)  
# 筛选出以.docx结尾的文件  
for file in files:  
    if file.endswith('.docx'):
        replace_and_renumber(os.path.join(current_directory, file), os.path.join(current_directory,f'sn-{file}'))
        #replaceName(os.path.join(current_directory, file), os.path.join(current_directory,f'sn-{file}'))